<template>
  <a-spin :spinning="confirmLoading">
    <!-- <j-form-container :disabled="formDisabled"> -->
      <a-form-model ref="form" :model="model" :rules="validatorRules">
        <div class="title">产品信息</div>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="产品名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <a-input v-model.trim="model.name" placeholder="请输入产品名称" :disabled="formDisabled" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="产品类目" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="categoryId">
              <a-tree-select
                allow-clear
                :disabled="formDisabled"
                v-model="model.categoryId"
                :replaceFields="replaceFields"
                :filterTreeNode="filterTreeNode"
                show-search
                style="width: 100%"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="treeData"
                placeholder="请选择产品类目"
                tree-default-expand-all
                :getPopupContainer="node => node.parentNode"
              >
              </a-tree-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="版型图片" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="images" class="version-img">
              <j-upload-oss v-model="model.images" fileType="image" bizPath="product" :number="20" :disabled="formDisabled"></j-upload-oss>
              <div style="position: absolute; left: 0; bottom: -14px;">请上传清晰地纯底色图片</div>
            </a-form-model-item>
          </a-col>
        </a-row>
        <div class="title" style="margin-bottom: 10px;">供应商信息</div>
        <a-row class="custom-table-header">
          <a-col :span="4">供应商</a-col>
          <a-col :span="4">价格</a-col>
          <a-col :span="4">尺码表</a-col>
          <a-col :span="4">使用面料</a-col>
          <a-col :span="4">参考重量</a-col>
          <a-col :span="4">操作</a-col>
        </a-row>
        <a-row class="custom-table-table" v-for="(domain, index) in model.domains" :key="index">
          <a-col :span="4">
            <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="{xs: { span: 24 }, sm: { span: 24 }}" :prop="'domains.' + index + '.supplierName'"
              :rules="{
                required: true,
                message: '请输入供应商！',
                trigger: 'change',
              }"
            >
              <a-input v-model.trim="domain.supplierName" placeholder="请输入供应商" style="width: 90%; margin-left: 5%;" :disabled="formDisabled" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="4">
            <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="{xs: { span: 24 }, sm: { span: 24 }}" :prop="'domains.' + index + '.price'"
              :rules="{
                required: true,
                message: '请输入价格！',
                trigger: 'change',
              }"
            >
              <a-input-number v-model="domain.price" placeholder="请输入价格" style="width: 70%; margin-left: 5%; margin-right: 5px;" :disabled="formDisabled" />元
            </a-form-model-item>
          </a-col>
          <a-col :span="4" class="custom-image">
            <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="{xs: { span: 24 }, sm: { span: 24 }}" :prop="'domains.' + index + '.sizeImage'"
              :rules="{
                required: true,
                message: '请上传尺码表！',
                trigger: 'change',
              }"
            >
              <j-upload-oss fileType="image" bizPath="product" :number="1" v-model="domain.sizeImage" v-if="!domain.sizeImage"></j-upload-oss>
              <div v-else  class="image">
                <img :src="domain.sizeImage" @click="handlePreview(domain.sizeImage)">
                <a-icon type="download" @click="handleDownload(domain.sizeImage)" />
                <a-icon type="delete" @click="handleDelete(index)" v-if="!formDisabled" />
              </div>
            </a-form-model-item>
          </a-col>
          <a-col :span="4">
            <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="{xs: { span: 24 }, sm: { span: 24 }}" :prop="'domains.' + index + '.fabric'"
              :rules="{
                required: true,
                message: '请输入使用面料！',
                trigger: 'change',
              }"
            >
              <a-input v-model.trim="domain.fabric" placeholder="请输入使用面料" style="width: 90%; margin-left: 5%;" :disabled="formDisabled" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="4">
            <a-form-model-item label="" :labelCol="labelCol" :wrapperCol="{xs: { span: 24 }, sm: { span: 24 }}" :prop="'domains.' + index + '.referenceWeight'"
            >
              <a-input-number v-model="domain.referenceWeight" placeholder="请输入参考重量" style="width: 70%; margin-left: 5%; margin-right: 5px;" :disabled="formDisabled" />克
            </a-form-model-item>
          </a-col>
          <a-col :span="4">
            <a-icon
              v-if="model.domains.length > 1 && !formDisabled"
              class="dynamic-delete-button"
              type="minus-circle-o"
              :disabled="model.domains.length === 1"
              @click="removeDomain(domain)"
            />
          </a-col>
        </a-row>
        <a-form-model-item v-if="!formDisabled">
          <a-button type="dashed" style="width: 100%;" @click="addDomain">
            <a-icon type="plus" />新增供应商
          </a-button>
        </a-form-model-item>
      </a-form-model>
    <!-- </j-form-container> -->
  </a-spin>
</template>

<script>
  import { httpAction, getAction, putFormAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'
  import { JVXETypes } from '@/components/jeecg/JVxeTable'
  import { productMixins } from '@/views/productLibrary/mixins/productMixins'
  export default {
    name: 'ProductLibraryVersionForm',
    mixins:[productMixins],
    components: {
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        model:{},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
          name: [
            { required: true, message: '请输入产品名称!'},
          ],
          categoryId: [
            { required: true, message: '请选择产品类目!'},
          ],
          images: [
            { required: true, message: '请上传版型图片!'},
          ]
        },
        url: {
          add: "/hzkj-product/product/productLibrary/pattern/add",
          edit: "/hzkj-product/product/productLibrary/pattern/edit",
          queryById: "/hzkj-product/product/productLibrary/pattern/queryById",
          confirm: "/hzkj-product/product/productLibrary/pattern/confirm",
          reject: "/hzkj-product/product/productLibrary/pattern/reject"
        }
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      }
    },
    created () {
      //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      add () {
        this.edit(this.modelDefault);
      },
      edit (record) {
        this.model = Object.assign({
          domains: [
            {
              supplierName: '',
              price: '',
              sizeImage: '',
              fabric: '',
              referenceWeight: ''
            }
          ]
        }, record);
        if(this.model.id){
          this.queryById();
        }
        this.loadData_('', 'queryMyCategory', this.model.categoryId);
        this.visible = true;
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        that.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!that.model.id){
              httpurl+=that.url.add;
              method = 'post';
            }else{
              httpurl+=that.url.edit;
              method = 'put';
            }
            that.model.patternSupplierList = that.model.domains;
            httpAction(httpurl,that.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
         
        })
      },
      queryById(){
        getAction(this.url.queryById, { id: this.model.id }).then((res) => {
          if(res.success){
            this.model.domains = (res.result && res.result.patternSupplierList) || [];
          }else{
            this.$message.warning(res.message);
          }
        })
      },
      handleReview(type){
        let httpurl = '';
        if(type === '通过'){
          httpurl+=this.url.confirm;
        }else if(type === '驳回'){
          httpurl+=this.url.reject;
        }
        putFormAction(httpurl, { id: this.model.id }).then((res)=>{
          if(res.success){
            this.$message.success(res.message);
            this.$emit('ok');
          }else{
            this.$message.warning(res.message);
          }
        })
      },
      removeDomain(item) {
        let index = this.model.domains.indexOf(item);
        if (index !== -1) {
          this.model.domains.splice(index, 1);
        }
      },
      addDomain() {
        this.model.domains.push(
          {
            supplierName: '',
            price: '',
            sizeImage: '',
            fabric: '',
            referenceWeight: ''
          }
        );
      },
      handlePreview(url){
        if(url){
          this.$viewerApi({images: [url]});
        }
      },
      async handleDownload(url){
        try {
          const response = await fetch(url);
          if(!response.ok){
            this.$message.warning('下载失败!');
            return;
          }
          const blob = await response.blob();
          const link = document.createElement('a');
          link.href = URL.createObjectURL(blob);
          link.download = url.split('/').pop();
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
        } catch (error) {
          this.$message.warning('下载失败!');
        }
      },
      handleDelete(index){
        this.model.domains.splice(index, 1, {
          ...this.model.domains[index],
          sizeImage: ''
        })
      }
    }
  }
</script>

<style lang="less" scoped>
.title{
  font-weight: 700;
  color: #000;
  display: flex;
  align-items: center;
  &::before{
    content: '';
    display: inline-block;
    width: 3px;
    height: 16px;
    background-color: #1890FF;
    margin-right: 6px;
  }
}
.j-vxe-table{
  /deep/.ant-upload.ant-upload-select-picture-card, /deep/.ant-upload-list-picture-card-container{
    margin: 8px 0;
  }
}
.version-img{
  /deep/.ant-form-item-label{
    width: 80px;
  }
  /deep/.ant-form-item-control-wrapper{
    width: calc(100% - 80px);
  }
}
.custom-table-header{
  &>div{
    color: rgba(0, 0, 0, 0.85);
    font-weight: 500;
    text-align: center;
    background: #fafafa;
    border: 1px solid #e8e8e8;
    border-right: 0;
    transition: background 0.3s ease;
    padding: 12px 8px;
    font-size: 12px;
  }
  &>div:last-child{
    border-right: 1px solid #e8e8e8;
  }
}
.custom-table-table{
  .ant-form-item{
    margin: 10px 0 5px;
    /deep/.ant-upload.ant-upload-select-picture-card, /deep/.ant-upload-list-picture-card-container, /deep/.ant-upload-list-item, .image img{
      width: 30px;
      height: 30px;
      border-radius: 4px;
      cursor: pointer;
      object-fit: cover;
      padding: 0;
      .ant-upload-text, .ant-upload-list-item-uploading-text{
        display: none;
      }
      .ant-upload{
        padding: 0;
      }
    }
    .image{
      text-align: center;
      .anticon{
        margin-left: 6px;
        cursor: pointer;
      }
    }
    /deep/.has-error .ant-form-explain{
      margin-left: 5%;
    }
    /deep/.ant-form-item-control{
      line-height: inherit;
    }
  }
}
.custom-image{
  /deep/.ant-upload.ant-upload-select-picture-card{
    margin: 0 0 0 50%;
    transform: translate(-50%, 0);
  }
}
.dynamic-delete-button{
  margin: 18px 50%;
  transform: translate(-50%, 0);
}
</style>